<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <script>
            let arr = [1, 2, 3, 2, 5];
            // 从指定索引（默认索引为arr.length）后往前面找
            console.log(arr.lastIndexOf(2, -1)); // 3
            console.log(arr.lastIndexOf(2, 2)); // 1
            console.log(arr.lastIndexOf(2)); // 3
            console.log(arr.lastIndexOf(2, -5)); // -1

            Array.prototype.myLastIndexOf = function (target, start = this.length - 1) {
                // 负数与数组长度相加后若是正数则作为开始查找位置，若是负数则直接返回 -1
                if (start < 0) {
                    start = start + this.length;
                    if (start < 0) {
                        return -1;
                    }
                }
                // 正数超出数组索引则从最末尾开始查找
                if (Math.abs(start) > this.length) start = this.length - 1;
                for (; start > 0; start--) {
                    if (this[start] == target) {
                        return start;
                    }
                }
                return -1;
            };
            console.log(arr.myLastIndexOf(2, -1)); // 3
            console.log(arr.myLastIndexOf(2, 2)); // 1
            console.log(arr.myLastIndexOf(2)); // 3
            console.log(arr.myLastIndexOf(2, -5)); // -1
        </script>
    </body>
</html>
